package servlet.environment;

import com.alibaba.fastjson.JSON;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * servlet.environment
 * User: 李雨行
 * Date: 2024/12/20 19:50
 * motto:   沉淀哥
 * Description:
 * Version: V1.0
 */
public class TianAPIService implements WeatherService {
    private static final String API_KEY = "5397b373c1eab2dd6f2692fe82b77021";

    @Override
    public String getAirQuality(String city){
        String urlString = null;
        try {
            urlString = "https://apis.tianapi.com/aqi/index?key=" + API_KEY + "&area="+ URLEncoder.encode(city,"utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        //  String urlString = "https://apis.tianapi.com/aqi/index?key=" + API_KEY + "&area="+city;
        System.out.println(urlString);
        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");

            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
//                int size = conn.getHeaderFieldInt("Content-Length", 1024);
//                byte[] bytes = new byte[size];
//                InputStream inputStream;
//                    inputStream = conn.getInputStream();
//                int o = inputStream.read(bytes);
//                inputStream.close(); // 流关闭后连接自动断开
//                String  data=new String(bytes, StandardCharsets.UTF_8);
//                System.out.println(data);
//                return  data;
                InputStream inputStream = conn.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    response.append(line);
                }
                return response.toString();
            } else {
                return "请求失败，响应码：" + responseCode;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "请求异常：" + e.getMessage();
        }
    }
}